package com.ls.lserp.modules.purchase.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.purchase.entity.PurchaseAdvance;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.purchase.service.PurchaseAdvanceService;
import com.ls.lserp.modules.purchase.service.PurchaseContractService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/purchase/advance/")
public class PurchaseAdvanceController extends BaseController {


    @Autowired
    private PurchaseAdvanceService purchaseAdvanceService;
    @Autowired
    private PurchaseContractService purchaseContractService;
    @Autowired
    Configuration freemarkerConfiguration;

    @ModelAttribute
    public PurchaseAdvance get(@RequestParam(required = false) String id) {

        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {

            // 执行查询语句 查询基本信息
            return purchaseAdvanceService.findByID (Long.parseLong (id));
        } else {

            // 若为空，实例化
            return new PurchaseAdvance ();
        }
    }

    /**
     * 采购预付款一览画面
     *
     * @return
     */
    @RequestMapping(value = {""})
    public String purchaseAdvance() {

        return "modules/purchase/purchaseAdvance";

    }

    /**
     * 拼接一览画面
     *
     * @param values
     * @return
     */
    @RequiresPermissions("purchase:advance:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                             Model model, String[] values) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "purchaseAdvance");
        // 画面取得的检索项目
        String advanceNO = purchaseAdvance.getAdvanceNO ();
        String contractMaterialNO = purchaseAdvance.getContractMaterialNO ();
        String ognizationName = purchaseAdvance.getOgnizationName ();
        String dateStart = purchaseAdvance.getDateStart ();
        String dateEnd = purchaseAdvance.getDateEnd ();
        String ulSelected = purchaseAdvance.getUlSelected ();
        purchaseAdvance.setDeleteFlag ("0");
        if ("2".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_10";
            purchaseAdvance.setUlSelected (ulSelected);

        } else if ("1".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_20";
            purchaseAdvance.setUlSelected (ulSelected);

        } else if ("0".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_30";
            purchaseAdvance.setUlSelected (ulSelected);

        } else if ("5".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_00";
            purchaseAdvance.setUlSelected (ulSelected);

        } else if ("4".equals (ulSelected)) {
            ulSelected = "-1";
            purchaseAdvance.setUlSelected (ulSelected);
            purchaseAdvance.setDeleteFlag ("1");

        }
        // 拼接字符串供分页使用
        String searchParam = "&advanceNO=" + advanceNO + "&contractMaterialNO=" + contractMaterialNO + "&ognizationName=" + ognizationName + "&dateStart=" + dateStart + "&dateEnd=" + dateEnd + "&ulSelected=" + ulSelected;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page <PurchaseAdvance> page = purchaseAdvanceService.findPurchaseAdvanceList (new Page <PurchaseAdvance> (request, response),
                purchaseAdvance);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("advanceList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("purchaseAdvanceList.ftl"), map);
        listMap.put ("purchaseAdvance", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }


    /**
     * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     *
     * @param filePath
     * @return html
     */
    public String readTxtFile(String filePath) {
        String strHtml = "";
        try {
            String encoding = "UTF-8";
            File file = new File (filePath);
            // 判断文件是否存在
            if (file.isFile ()) {
                InputStreamReader read = new InputStreamReader (
                        // 考虑到编码格式
                        new FileInputStream (file), encoding);
                BufferedReader bufferedReader = new BufferedReader (read);
                String lingText = null;
                while ((lingText = bufferedReader.readLine ()) != null) {
                    strHtml += lingText;
                }
                read.close ();
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return strHtml;
    }

    /**
     * 采购合同信息一览窗口
     *
     * @return
     */
    @RequiresPermissions("purchase:advance:view")
    @RequestMapping(value = {"contractList"})
    public String contractList(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                               Model model) {
        return "modules/purchase/purchaseAdvanceCreate2";
    }

    /**
     * 创建采购预付款信息窗口
     *
     * @return
     */
    @RequiresPermissions("purchase:advance:view")
    @RequestMapping(value = {"createAdvance"})
    public String createAdvance(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                                Model model) {
        purchaseAdvance.preInsert ();
        model.addAttribute ("purchaseAdvance", purchaseAdvance);
        return "modules/purchase/purchaseAdvanceCreate";
    }

    /**
     * 查看一条采购预付款信息
     *
     * @return
     */
    @RequiresPermissions("purchase:advance:view")
    @RequestMapping(value = {"viewAdvance"})
    public String viewAdvance(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                              Model model) {
        PurchaseContract purchaseContract = new PurchaseContract ();
        purchaseContract.setId (Long.parseLong (purchaseAdvance.getContractMaterialID ()));
        List <PurchaseContract> materialList = purchaseContractService.findMaterialByIdOrder (purchaseContract);
        purchaseContract.setMaterialList (materialList);
        purchaseAdvance = purchaseAdvanceService.getAdvance (purchaseAdvance);
        model.addAttribute ("purchaseAdvance", purchaseAdvance);
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseAdvanceShow";
    }

    /**
     * 编辑采购预付款信息窗口
     *
     * @return
     */
    @RequiresPermissions("purchase:advance:view")
    @RequestMapping(value = {"editAdvance"})
    public String editAdvance(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                              Model model) {
        PurchaseContract purchaseContract = new PurchaseContract ();
        purchaseContract.setId (Long.parseLong (purchaseAdvance.getContractMaterialID ()));
        List <PurchaseContract> materialList = purchaseContractService.findMaterialByIdOrder (purchaseContract);
        purchaseContract.setMaterialList (materialList);
        purchaseAdvance = purchaseAdvanceService.getAdvance (purchaseAdvance);
        model.addAttribute ("purchaseAdvance", purchaseAdvance);
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseAdvanceCreate";
    }

    /**
     * 创建编辑保存仓库信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:advance:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                       Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (purchaseAdvance.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            PurchaseAdvance purchaseAdvanceNew = get (purchaseAdvance.getId ().toString ());
            // 判断数据是否删除
            if (purchaseAdvanceNew == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseAdvanceNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (purchaseAdvance.getVersion () == get (purchaseAdvance.getId ().toString ()).getVersion ()) {

                // 版本号加1
                purchaseAdvance.setVersion (purchaseAdvance.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        purchaseAdvanceService.savePurchaseAdvance (purchaseAdvance);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 提交采购预付款信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:advance:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (purchaseAdvance.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            PurchaseAdvance purchaseAdvanceNew = get (purchaseAdvance.getId ().toString ());
            // 判断数据是否删除
            if (purchaseAdvanceNew == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseAdvanceNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (purchaseAdvance.getVersion () == get (purchaseAdvance.getId ().toString ()).getVersion ()) {

                // 版本号加1
                purchaseAdvance.setVersion (purchaseAdvance.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        purchaseAdvanceService.deletePurchaseAdvance (purchaseAdvance);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 提交采购预付款信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:advance:edit")
    @RequestMapping(value = "commit")
    @ResponseBody
    public String commit(PurchaseAdvance purchaseAdvance, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (purchaseAdvance.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            PurchaseAdvance purchaseAdvanceNew = get (purchaseAdvance.getId ().toString ());
            // 判断数据是否删除
            if (purchaseAdvanceNew == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseAdvanceNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (purchaseAdvance.getVersion () == get (purchaseAdvance.getId ().toString ()).getVersion ()) {

                // 版本号加1
                purchaseAdvance.setVersion (purchaseAdvance.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        purchaseAdvanceService.commitPurchaseAdvance (purchaseAdvance);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 审核页面
     *
     * @param purchaseAdvance
     * @param model
     * @return
     */
    @RequiresPermissions("purchase:advance:audit")
    @RequestMapping(value = "audit")
    public String audit(PurchaseAdvance purchaseAdvance, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        // 履历一览取得
        AuditInfo auditInfo = new AuditInfo ();
        // id
        auditInfo.setAuditRelateId (purchaseAdvance.getId ());
        // 阶段
        auditInfo.setAuditPhaseCd (ResourcesUtil.getConfig ("audit_phase_advance"));
        AuditInfo resultInfo = purchaseAdvanceService.findAuditInfo (auditInfo);


        resultInfo.setAuditRelateId (purchaseAdvance.getId ());

        resultInfo.setAuditRelateNo (purchaseAdvance.getAdvanceNO ());

        resultInfo.setAuditPhaseCd (ResourcesUtil.getConfig ("audit_phase_advance"));

        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("auditInfo", resultInfo);

        // 返回页面地址
        return "modules/order/auditInfo";
    }

    /**
     * 保存履历信息
     *
     * @param auditInfo
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:advance:edit")
    @RequestMapping(value = "saveAudit")
    @ResponseBody
    public String saveAudit(AuditInfo auditInfo, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {

        // 是否需要更新样品需求状态
        boolean isUpdateStatus = false;

        // 判断数据是否删除
        PurchaseAdvance purchaseAdvance = get (Long.toString (auditInfo.getAuditRelateId ()));
        // 判断数据是否删除
        if (purchaseAdvance.getAdvanceNO () == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseAdvance.getDeleteFlag ())) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }

        // 审核结果已经通过,返回错误提示信息
        AuditInfo pAuditResult = new AuditInfo ();
        pAuditResult.setAuditPhaseCd (auditInfo.getAuditPhaseCd ());
        pAuditResult.setAuditRelateId (auditInfo.getAuditRelateId ());
        if (purchaseAdvanceService.getAuditResult (pAuditResult) > 0) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }


        // 保存样品数据
        purchaseAdvanceService.saveAuditInfo (auditInfo, isUpdateStatus);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("audit_ok_msg")));

    }
    @RequiresPermissions("purchase:advance:edit")
	@ResponseBody
	@RequestMapping(value = "exportFile")
	public String exportFile(PurchaseContract purchaseContract,PurchaseAdvance purchaseAdvance ,HttpServletResponse response){
		try {
            // 模版
            String basePath = SystemPath.getClassPath();
            String tempFilePath = "/" + basePath + "purchaseAdvance.xlsx";
            ExcelTemplate handle = this.purchaseAdvanceService.exportOrderMateriel(purchaseContract,purchaseAdvance, tempFilePath);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + purchaseAdvance.getContractMaterialNO()  +".xlsx");
            OutputStream os = response.getOutputStream();
            // 写到输出流并关闭资源
            handle.writeAndClose(tempFilePath, os);
            os.flush();
            os.close();
            handle.readClose(tempFilePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
}
